using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options =>
{
    // Match the default System.Text.Json web conventions.
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

var app = builder.Build();

app.MapPost("/webhook/callback", (WebhookPayload payload, HttpRequest request) =>
{
    var signature = request.Headers["X-NotifyCenter-Signature"].FirstOrDefault() ?? "<none>";
    var timestamp = DateTimeOffset.UtcNow.ToString("O");
    var payloadJson = JsonSerializer.Serialize(payload, new JsonSerializerOptions
    {
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
    });

    Console.WriteLine($"[{timestamp}] Webhook signature: {signature}");
    Console.WriteLine(payloadJson);

    return Results.Ok(new
    {
        Message = "Webhook received",
        ReceivedAtUtc = timestamp
    });
});

app.Run();

public record WebhookPayload(
    long RecordId,
    long ProjectId,
    long NotificationRuleId,
    string NotificationName,
    string NotificationType,
    int NotificationTypeValue,
    string Status,
    int StatusValue,
    string StatusMessage,
    DateTimeOffset OccurredAtUtc);
